package com.example.homework8.sqliteroom;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.room.RoomDatabase;

import com.example.homework8.R;

import java.util.List;

public class Room extends Fragment {
    public Room(){
        super(R.layout.room);
    }

    private TextView output;

    public void onViewCreated(@NonNull View view, @Nullable Bundle saveInstanceState) {
        super.onViewCreated(view, saveInstanceState);

        EditText Name = getActivity().findViewById(R.id.name);
        EditText Age = getActivity().findViewById(R.id.age);
        output = getActivity().findViewById(R.id.output);
        Button insert = (Button)getActivity().findViewById(R.id.insert);
        Button query = (Button)getActivity().findViewById(R.id.query);

        MyRoomDatabase db = MyRoomDatabase.getInstance(getActivity());
        showUsers(db.UserDao().getALL());

        insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                User user = new User();
                user.username = Name.getText().toString();
                user.age = Integer.parseInt(Age.getText().toString());
                db.UserDao().insert(user);
                Toast.makeText(getActivity(), "添加成功!", Toast.LENGTH_SHORT).show();
                showUsers(db.UserDao().getALL());
                db.close();
            }
        });

        query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showUsers(db.UserDao().searchUserByAge(18));
                db.close();
            }
        });
    }
    private void showUsers(List<User> users){
        StringBuilder stringBuilder = new StringBuilder();
        for(User user:users){
            stringBuilder.append("id:").append(user.id)
                    .append("  username:").append(user.username)
                    .append("  age:").append(user.age)
                    .append("\n");
        }
        output = getActivity().findViewById(R.id.output);
        output.setText(stringBuilder.toString());
    }
}